﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows.Threading;

using QuantumBitDesigns.Core;

namespace Jarvis.Sensors
{
    class SensorNotifier
    {
        private static SensorNotifier instance = null;

        public ObservableList<SensorUpdate> updates;
        public SensorsUpdatedHandler SensorsUpdate;

        public  void setDispatcher (Dispatcher dispatcher)
        {
            this.updates = new ObservableList<SensorUpdate>(dispatcher);
        }

        public static SensorNotifier Instance
        {
            get
            {
                if (instance == null)
                    instance = new SensorNotifier();

                return instance;
            }
        }

        public void addUpdate(Sensor sensor, object value)
        {
            if (updates == null)
                return;

            lock (updates)
            {
                var result = from update in updates
                             where update.sensor.name == sensor.name
                             select update;

                List<SensorUpdate> matches = new List<SensorUpdate>();

                if (value != null)
                {
                    if (result.ToArray().Length > 0)
                    {
                        foreach (SensorUpdate update in result)
                        {
                            update.sensorValue = value;
                            update.sensor = sensor;
                        }
                    }
                    else
                    {
                        updates.Add(new SensorUpdate(sensor, value));
                    }
                }
                else
                {
                    foreach (SensorUpdate match in matches)
                        updates.Remove(match);
                }

                SensorsUpdated(new EventArgs());
            }
        }

        public Dictionary<String, object> getState()
        {
            if (updates == null)
                return null;

            Dictionary<String, object> state = new Dictionary<String, object>();

            lock (updates)
            {
                foreach (SensorUpdate update in updates)
                {
                    state[update.name] = update.sensorValue;
                }
            }

            return state;
        }

        public delegate void SensorsUpdatedHandler(object obj, EventArgs eventArgs);

        protected virtual void SensorsUpdated(EventArgs eventArgs)
        {
            if (SensorsUpdate != null)
            {
                SensorsUpdate(this, eventArgs);
            }
        }
    }
}
